function [idat sandbox] = fsb_crop_brain(idat,sandbox)

% FSB : remove empty space around a brain
%
% EXAMPLE:
% [idat sandbox] = fsb_crop_brain(idat,sandbox)
%
% INPUT:
% idat:         3D or 4D image data
% sandbox:         sandbox struct
%
% OUTPUT:
% A 4D- Volume with empty space removed
%
% CALLED BY:
% FSB.m
%
% NOTES:
% Looks for empty space around the brain, and removes it.
%
% Copyright 2010 MPI for Biological Cybernetics
% Author: Steffen Stoewer
% License:GNU GPL, no express or implied warranties
% 
% $Revision 1.0
%
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

if ndims(idat) == 4 && exist('sandbox','var');

    %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    % if a 4-D image file and a sandbox struct have been provided
    %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    %idat_3 = (idat(:,:,:,1));
    idat_3 = mean(idat,4);
    idat_3(idat_3==0)=NaN;
    s_3_idat = nansum(idat_3,3);
    s_2_idat = nansum(idat_3,1);
    s_2_idat = squeeze(s_2_idat);
    x=nanmean(s_3_idat,1);
    y=nanmean(s_3_idat,2);
    z=nanmean(s_2_idat,1);
    xi = find(x~=0);
    yi = find(y~=0);
    zi = find(z~=0);

    idat = idat(yi,xi,zi,:);
try
    
    sandbox.stats.r_cor=sandbox.stats.r_cor(yi,xi,zi,:);
    sandbox.stats.brob=sandbox.stats.brob(yi,xi,zi,:);
    sandbox.stats.b_est =sandbox.stats.b_est(yi,xi,zi,:);
    sandbox.stats.p_rob=sandbox.stats.p_rob(yi,xi,zi,:);
    sandbox.stats.rob_est=sandbox.stats.rob_est(yi,xi,zi,:);
    sandbox.stats.rob_prob=sandbox.stats.rob_prob(yi,xi,zi,:);
    sandbox.stats.glm_prob=sandbox.stats.glm_prob(yi,xi,zi,:);
    sandbox.stats.t_test=sandbox.stats.t_test(yi,xi,zi,:);
    
catch
    sandbox.stats = [];
end

else

    %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    % if a 3-D image has been provided
    %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    s_3_idat = nansum(idat,3);
    s_2_idat = nansum(idat,1);
    s_2_idat = squeeze(s_2_idat);

    x=nanmean(s_3_idat,1);
    y=nanmean(s_3_idat,2);
    z=nanmean(s_2_idat,1);

    idat((y==0),:,:)=[];
    idat(:,(x==0),:)=[];
    idat(:,:,(z==0))=[];
    sandbox = struct;

end

end
